package com.itheima.reggie.controller;


import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession httpSession;
    //登录
    //后面Post  Put 请求,前端都是使用请求体提交的参数, 后端只能使用@RequestBody接收
    //此注解只能修饰一个实体类或者Map
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //1.接收参数
        String username = map.get("username");
        String password = map.get("password");
        //2.调用service登录操作
        ResultInfo resultInfo = employeeService.login(username,password);
        //3.如果用户登录成功了，就将resultInfo保存到httpSession中去
        if (resultInfo.getCode()==1){
            Employee employee = (Employee)resultInfo.getData();
            httpSession.setAttribute(Constant.SESSION_EMPLOYEE,employee);
        }
        //返回resultInfo对象
        return resultInfo;
    }
    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //销毁session对象
        httpSession.invalidate();
        //返回ResultInfo
        return ResultInfo.success(null);
    }
    //通过name查找
    @GetMapping("/employee/find")
    public ResultInfo find(String name){

        List<Employee> employeeList =  employeeService.findByName(name);

        return ResultInfo.success(employeeList);
    }

    //添加员工
    @PostMapping("/employee")
    public ResultInfo addEmployee(@RequestBody Employee employee){

        employeeService.addEmployee(employee);
        return ResultInfo.success(null);
    }

    //反显
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee =  employeeService.findById(id);

        return ResultInfo.success(employee);
    }

    //更新和更改状态
    @PutMapping("/employee")
    public ResultInfo putEmployee(@RequestBody Employee employee){
        System.out.println("1");
        employeeService.putEmployee(employee);
        return ResultInfo.success(null);
    }
}
